package CRUD;

// default package
// Generated Apr 21, 2011 3:13:26 PM by Hibernate Tools 3.3.0.GA

import Utility.HtmlEncode;
import Utility.SessionFactoryUtil;
import java.util.List;
import javax.naming.InitialContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import xmlMapping.Post;
import xmlMapping.Thread;
/**
 * Home object for domain model class Post.
 * @see .Post
 * @author Hibernate Tools
 */
public  class PostHome {

	private static final Log log = LogFactory.getLog(PostHome.class);


      	private    Session session;
        
        public void releaseConnection()
        {
        session.close();
        }
        

    public PostHome() {
       if(session==null|| !session.isOpen())
           
        session=SessionFactoryUtil.getSessionFactory().openSession();
       
    }
 
    
	public synchronized   void persist(Post transientInstance) {
           
                session.beginTransaction();
		log.debug("persisting Post instance");
		try {
                    
                 //   transientInstance.setBody( HtmlEncode.Encode(transientInstance.getBody()));
			session.persist(transientInstance);
                         
                        session.getTransaction().commit();
                       
			log.debug("persist successful");
		} catch (RuntimeException re) {
			log.error("persist failed", re);
			throw re;
		}
	}
        
        public  synchronized    Integer Save(Post transientInstance)
          {
                
                 session.beginTransaction();
                Integer result=0;
		log.debug("persisting Post instance");
		try {
			result= (Integer) session.save(transientInstance);
                         
                         session.getTransaction().commit();
                       
			log.debug("persist successful");
		} catch (RuntimeException re) {
			log.error("persist failed", re);
			throw re;
		
                }
      return   result;
        }

	public  synchronized  void attachDirty(Post instance) {
          //  session=  new SessionFactoryUtil(). session;
                 session.beginTransaction();
		log.debug("attaching dirty Post instance");
		try {
			 session.saveOrUpdate(instance);
                         
                          session.getTransaction().commit();
                        
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

        
        
        
	public  synchronized  void attachClean(Post instance) {
            
                 session.beginTransaction();
		log.debug("attaching clean Post instance");
		try {
			 session.lock(instance, LockMode.NONE);
                      
                          session.getTransaction().commit();
                        
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public  synchronized  void delete(Post persistentInstance) {
          //  session=  session;
                 session.beginTransaction();
		log.debug("deleting Post instance");
		try {
			 session.delete(persistentInstance);
                       
                          session.getTransaction().commit();
                         
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public  synchronized  Post merge(Post detachedInstance) {
          //  session=  session;
                 session.beginTransaction();
		log.debug("merging Post instance");
		try {
			Post result = (Post)  session.merge(detachedInstance);
                        
                          session.getTransaction().commit();
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public  synchronized  Post findById(java.lang.Integer id) {
            System.out.println(" find by id"+id);
            //session=  session;
              // session.beginTransaction();
		log.debug("getting Post instance with id: " + id);
		try {
			Post instance = (Post)  session.get(
					Post.class, id);
			if (instance == null) {
                            System.out.println(" in find by id and instance is null ");
				log.debug("get successful, no instance found");
			} else {
                            System.out.println(" in find by id and instance is not  null ");
				log.debug("get successful, instance found");
			}
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public  synchronized  List findByExample(Post instance) {
           // session=  session;
               session.beginTransaction();
		log.debug("finding Post instance by example");
		try {
			List results =  session.createCriteria(
					Post.class).add(Example.create(instance)).list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

        public  synchronized  List getPosts(Thread thread){
//            session=  session;
               session.beginTransaction();
            Criteria crit=   session.createCriteria(Post.class);
            Criterion threadId=Restrictions.eq("thread", thread);
            crit.add(threadId);
            crit.addOrder(Order.asc("postId"));
            return crit.list();
        }


        public List getPostsPage(Thread thread,int pageNumber){
            //session= SessionFactoryUtil.getSessionFactory().getCurrentSession();
                session.beginTransaction();
            Criteria crit=  session.createCriteria(Post.class);
            Criterion threadId=Restrictions.eq("thread", thread);
            crit.add(threadId);
            crit.addOrder(Order.desc("postId"));
            crit.setFirstResult((pageNumber-1)*10);
            crit.setMaxResults(10);
            return crit.list();
        }

        public int getCount(int thId){
           // session= SessionFactoryUtil.getSessionFactory().getCurrentSession();
                session.beginTransaction();
                Query query=session.createQuery("select count(*) from Post where thread_id = :thid");
                query.setInteger("thid", thId);
                return Integer.parseInt(query.uniqueResult().toString());
        }

        /*public List getForumPosts(){
            session= SessionFactoryUtil.getSessionFactory().getCurrentSession();
                session.beginTransaction();
            Criteria crit=  session.createCriteria(Post.class);*/

        public  synchronized  List getForumPosts(){
//            session=  session;
               session.beginTransaction();
            Criteria crit=   session.createCriteria(Post.class);

             crit.addOrder(Order.asc("postId"));
            return crit.list();
        }

        public  synchronized  List search(String key){
//            session=  session;
                 session.beginTransaction();
            Criteria crit=   session.createCriteria(Post.class);
            Criterion title=Restrictions.like("title", key,MatchMode.ANYWHERE);
            crit.add(title);
            return crit.list();
        }
}
